import { defineStore } from 'pinia'

export const useIframeStore = defineStore('iframe', {
	state: () => ({
		iframeList: []
	}),
	
	getters: {
		// 获取iframe列表
		getIframeList: (state) => state.iframeList,
		
		// 获取iframe数量
		getIframeCount: (state) => state.iframeList.length,
		
		// 根据路径查找iframe
		findIframeByPath: (state) => (path) => {
			return state.iframeList.find(item => item.path === path)
		}
	},
	
	actions: {
		// 设置iframe列表（替换模式）
		setIframeList(route) {
			this.iframeList = []
			this.iframeList.push(route)
		},
		
		// 添加iframe到列表
		pushIframeList(route) {
			const target = this.iframeList.find(item => item.path === route.path)
			if (!target) {
				this.iframeList.push(route)
			}
		},
		
		// 从列表中移除iframe
		removeIframeList(route) {
			this.iframeList.forEach((item, index) => {
				if (item.path === route.path) {
					this.iframeList.splice(index, 1)
				}
			})
		},
		
		// 刷新指定iframe
		refreshIframe(route) {
			this.iframeList.forEach((item) => {
				if (item.path == route.path) {
					const url = route.meta.url
					item.meta.url = ''
					setTimeout(() => {
						item.meta.url = url
					}, 200)
				}
			})
		},
		
		// 清空iframe列表
		clearIframeList() {
			this.iframeList = []
		}
	}
})